//
//  Singleton.m
//  LiveStar
//
//  Created by SKT1 on 2016/12/5.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "Singleton.h"

@implementation Singleton

+ (Singleton *)shareSingleton {
    static Singleton *userSingleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userSingleton = [[Singleton alloc] init];
    });
    return userSingleton;
}


- (NSString *)filePath:(NSString *)fileName
{
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [docPath stringByAppendingPathComponent:fileName];
    return filePath;
    
    
}
//归档 数组
- (void)archiverWithArray:(NSMutableArray *)aArray fileName:(NSString *)fileName
{
    NSMutableData * data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:aArray forKey:@"array"];
    [archiver finishEncoding];
    
    BOOL result = [data writeToFile:[self filePath:fileName] atomically:YES];
    if (result) {
        NSLog(@"写入成功");
    }
}

//解档
- (NSMutableArray *)unArchiverWithFileName:(NSString *)fileName
{
    NSData * data = [[NSData alloc] initWithContentsOfFile:[self filePath:fileName]];
    NSKeyedUnarchiver * unarchier = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray * array = [unarchier decodeObjectForKey:@"array"];
    
    [unarchier finishDecoding];
    return [NSMutableArray arrayWithArray:array];
}

- (void)archiverWithModel:(UserModel *)userModel fileName:(NSString *)fileName
{
    NSMutableData * data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:userModel forKey:@"user"];
    [archiver finishEncoding];
    
    BOOL result = [data writeToFile:[self filePath:fileName] atomically:YES];
    if (result) {
        NSLog(@"写入成功");
    }
}

//解档
- (UserModel *)unArchiverUserModelWithFileName:(NSString *)fileName
{
    NSData * data = [[NSData alloc] initWithContentsOfFile:[self filePath:fileName]];
    NSKeyedUnarchiver * unarchier = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    UserModel * model = [unarchier decodeObjectForKey:@"user"];
    
    [unarchier finishDecoding];
    return model;
}

//偏好设置存储
- (void)SetDefaultsWithObject:(id)object Key:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:object forKey:key];
    [defaults synchronize];
}

//偏好设置取
- (instancetype)GetDefaultsWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    id objc = [defaults objectForKey:key];
    return objc;
}
@end
